package com.liu.spike.listener;

import com.alibaba.fastjson.JSONObject;
import com.liu.spike.common.KafkaTopic;
import com.liu.spike.entity.Order;
import com.liu.spike.entity.dto.ProductOrderDto;
import com.liu.spike.mapper.ProductMapper;
import com.liu.spike.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @className: com.liu.spike.listener.SplikeTopicListener
 * @description: TODO
 * @author: liu
 * @create: 2022-05-02 14:29
 */
@Slf4j
@Component
public class SplikeTopicListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductMapper productMapper;

//    尖峰 SPIKE_TOPIC
    @Transactional
    @KafkaListener(topics = KafkaTopic.SPIKE_TOPIC,groupId = "local")
    public void processMessage(ConsumerRecord<?, ?> record, Acknowledgment ack) {
        try {
            String msg = (String) record.value();
            ProductOrderDto productOrderDto = JSONObject.parseObject(msg, ProductOrderDto.class);
            log.info("用户:{} 秒杀商品:{} 成功",productOrderDto.getProductId(),productOrderDto.getUid());
            orderService.save(Order.builder().productId(productOrderDto.getProductId()).uid(productOrderDto.getUid()).build());
            productMapper.descStock(productOrderDto.getProductId());
//            减少 库存
            ack.acknowledge();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
